import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Checkbox, Form, Input, Modal, Row, Col, Alert} from 'antd';

@connect(state => ({
  role: state.role,
}))
@Form.create()
export default class MenuModal extends PureComponent {

  state = {
    checkedValues: []
  }

  componentDidMount() {
    const _this = this;
    const {dispatch, items, modalVisible} = this.props;
    if(modalVisible){
      dispatch({
        type: 'role/queryRoleMenu',
        payload: {roleId: items.id},
        callback: (result) => {
          _this.setState({checkedValues: result.rows})
        }
      });
    }
  }

  handleOk = () => {
    const {checkedValues} = this.state;
    const {form, handleSave} = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return
      }
      values.menus = checkedValues;
      handleSave(values, form);
    })
  }

  onChangeOne = (checkedValues) => {
    // console.log(checkedValues)
    this.setState({
      checkedValues:checkedValues
    })
  };

  render() {
    const {checkedValues} = this.state;
    const {form: {getFieldDecorator}, items, modalVisible, handleModalCancel, menuList} = this.props;

    let element;
    if (menuList) {
      element = menuList.map(obj =>
        <div style={{padding:10, borderRadius:5, backgroundColor:'#f5f5f5', marginBottom:10}}>
          <div><Checkbox value={obj.id} key={obj.id}>{obj.name}<span style={{fontSize:'smaller', color:'#ff4d4f'}}>(一级菜单)</span></Checkbox></div>
          {obj.children &&
          <div style={{paddingTop:10}}>
            <Row>
              {obj.children.map(item=><Col span={6}> <Checkbox value={item.id} key={item.id}>{item.name}</Checkbox></Col>)}
            </Row>
          </div>
          }
        </div>
      )
    }

    return (
      <div>
        <Modal
          title='配置菜单'
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={handleModalCancel}
          closable={false}
        >
          <Alert message="注：不要只勾选子菜单而忽略一级菜单，只单独勾选非一级菜单是不会渲染出来的！" type="warning" showIcon style={{marginBottom:10}} />
          <Form>
            {getFieldDecorator('id', {
              initialValue: items.id,
            })(
              <Input hidden={true}/>
            )}
            <Checkbox.Group value={checkedValues} onChange={this.onChangeOne} style={{width:'100%'}}>
              {element}
            </Checkbox.Group>
          </Form>
        </Modal>
      </div>
    );
  }
}
